package cn.amebius.simpledocker.thread;

import cn.amebius.simpledocker.exception.DockerErrorException;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.AttachContainerCmd;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.core.command.AttachContainerResultCallback;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 阿伟
 * @date 2023/9/6 19:29
 */
public class AttachConsoleThread extends Thread {

    private WebSocketSession session;

    private InputStream is;

    private DockerClient dc;

    private String containerId;

    public AttachConsoleThread(WebSocketSession session,InputStream is, DockerClient dc, String containerId) {
        this.session = session;
        this.is = is;
        this.dc = dc;
        this.containerId = containerId;
    }

    @Override
    public void run() {
        AttachContainerCmd acc = dc.attachContainerCmd(containerId);
        try {
            acc.withStdOut(true)
                    .withStdErr(true)
                    .withFollowStream(true)
                    .withStdIn(is)
                    .withLogs(true)
                    .exec(new AttachContainerResultCallback() {
                        @Override
                        public void onNext(Frame item) {;
                            try {
                                session.sendMessage(new TextMessage(item.getPayload()));
                            } catch (IOException e) {
                                throw new DockerErrorException("Docker异常：操作容器attach错误！");
                            }
                        }
                    }).awaitCompletion();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new DockerErrorException("Docker异常：操作容器attach错误！");
        }
    }
}
